<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\LuckMoney;
use App\Models\LuckMoneyLog;
use Illuminate\Support\Facades\DB;
use App\Libs\ApiMessage;

class LuckMoneyController extends Controller{
    // 拆红包首页
    public function index(Request $request){
        $id = $request->id;
        $open_id = $request->openid;
        $sign = $request->sign;

        // 判断是否存在活动
        if(!empty($id)){
            // 判断open_id 是否存在
            if(empty($open_id)){
                echo json_encode(['code'=>5001,'massage'=>'用户不存在','result'=>'']);
                exit();
            }
            // 搜索活动信息
            $activity_info = LuckMoney::get_activity_info($id);
            if(!empty($activity_info)){
                if(empty($sign)){
                    $sign = LuckMoneyLog::get_sign($id, $open_id);
                }

                if(!empty($sign)){
                    $check = $this->check_time($sign);

                    $user_list = LuckMoneyLog::get_user_list($sign); // 获取用户列表
                    $user_list = $this->object_array($user_list); // 转化为数组

                    $state = LuckMoneyLog::get_state($sign);
                    $res_state = $this->get_state($state,$open_id,$user_list);
                    // 第一次进入
                    $data['result'] = array(
                        'id' => $activity_info->id,
                        'state' => $res_state, //
                        'money' => $activity_info->money, // 金额
                        'share_number' => $activity_info->share_number, // 分享人数
                        'count_user_list' => count($user_list),
                        'use_number' => $activity_info->use_number, // 使用红包团数
                        'res_number' => $activity_info->number - $activity_info->use_number, // 使用红包团数
                        'share_img' => $activity_info->share_img, // 分享图片
                        'user_list' => $user_list,
                        'end_date' => date('Y-m-d H:i:s', $check['end_time']).'失效',
                        'end_time' => $check['end_time'],
                    );
                    if($check['code'] == false){
                        echo json_encode(['code'=>5003,'massage'=>'成功','result'=>$data['result']]);
                        exit();
                    }
                    echo json_encode(['code'=>200,'massage'=>'成功','result'=>$data['result']]);
                    exit();
                }else{
                    // 第一次进入
                    $data['result'] = array(
                        'id' => $activity_info->id,
                        'state' => $this->get_state(null), // 状态空
                        'money' => $activity_info->money, // 金额
                    );
                    echo json_encode(['code'=>200,'massage'=>'成功','result'=>$data['result']]);
                    exit();
                }
            }else{
                echo json_encode(['code'=>5002,'massage'=>'活动已过期','result'=>'']);
                exit();
            }
        }else{
            echo json_encode(['code'=>5000,'massage'=>'该活动不存在','result'=>'']);
            exit();
        }
    }

    // 判断时间是否
    public function check_time($sign){
        $data = DB::table('luckmoney_log')
            ->select('*')
            ->where(function($query)use($sign){
                $query -> where('sign', $sign);
                $query -> where('captain', 1);
            })->first();
        $temp = date('Y-m-d H:i:s', $data->created_at);
        $end_time = strtotime("$temp +1 day");
//        print_r($end_time);exit;
        $time = time();
        if($end_time > $time){
            // 通过
            $code = true;
        }else{
            // 失败
            DB::table('team_status')->where('sign',$sign)->update([
                'val' => 3,
            ]);
            $code = false;
        }
        $check = array(
            'code' => $code,
            'end_time' => $end_time,
        );
        return $check;
    }


    // obj转数组
    public function object_array($array) {
        if(is_object($array)) {
            $array = (array)$array;
        } if(is_array($array)) {
            foreach($array as $key=>$value) {
                $array[$key] = $this->object_array($value);
            }
        }
        return $array;
    }

    // 获取状态
    public function get_state($state, $open_id = '', $user_list = array()){
        if ($state == LuckMoneyLog::CREATE) {
            return null;
        }
        if ($state == LuckMoneyLog::WORKING) {
            $sign = false;
            $is_captain = false;
            foreach ($user_list as $obj) {
                if ($open_id == $obj['open_id']) {
                    $sign = true;
                    if ($obj['captain']) {
                        $is_captain = true;
                    }
                    break;
                }
            }
            if ($sign == false) {  //还没参与
                return 100;
            }
            if ($is_captain) {  //参与，并且是团长
                return 101;
            }
            if (!$is_captain && $sign) {   //参与，不是团长
                return 102;
            }
        }
        if ($state == LuckMoneyLog::SUCCESS) {
            $sign = false;
            foreach ($user_list as $obj) {
                if ($open_id === $obj['open_id']) {
                    $sign = true;
                    break;
                }
            }
            return ($sign === true) ? 200 : 201;
        }
        if ($state == LuckMoneyLog::FAIL) {
            return 5000;
        }
    }

    //检查上限
    public function checkout(Request $request) {
        $luckMoneyLog = new LuckMoneyLog();
        $result = $luckMoneyLog->checkout($request);
        if ($result !== true) {
            return $result->send();
        }
        return true;
    }

    //拆红包
    private function luck_money_add_handle(Request $request) {
        $luckMoneyLog = new LuckMoneyLog();
        if ($request->sign) {
            $res = $luckMoneyLog->get_luck_money_log_by_sign($request->sign);
        } else {
            $res = $luckMoneyLog->get_luck_money_log($request->aid);
        }
        if ($res->getCode() == '200') {
            $user_info = $this->get_user_info($request->openid);
            $data = array_merge($res->getData(),$user_info);
            $result = $luckMoneyLog->add_log($data);
            if ($result) {
                $luckMoney = new LuckMoneyLog();
                $send_data = $luckMoney->get_team_info($data['sign'],$data['luckmoney_id']);
                $message = new ApiMessage(ApiMessage::SUCCESS);
                $message->setData($send_data);
                return $message->send();
            } else {
                $message = new ApiMessage(ApiMessage::FAIL);
                return $message->send();
            }
        } else {
            return $res->send();
        }
    }

    // 添加拆红包
    public function luck_money_add(Request $request){
        $this->checkout($request);
        return $this->luck_money_add_handle($request);
    }

    //根据openid 获取用户信息
    private function get_user_info($id) {
        $object = DB::table("user")->select("username","head_ico","open_id")->where(["open_id"=>$id])->first();
        if ($object) {
            $res['username'] = $object->username;
            $res['head_ico'] = $object->head_ico;
            $res['open_id'] = $object->open_id;
            return $res;
        } else {
            return null;
        }
    }

    // 获取用户列表
    public function getUserList($open_id = '',$sign = ''){
        if(!empty($open_id)){
            $data = DB::table('user as a')
                ->select('*')
                ->leftJoin('luckmoney_log as b', 'a.open_id', '=', 'b.openid')
                ->where(function($query)use($open_id,$sign){
                    $query -> where('a.open_id', $open_id);
                    $query -> where('open_id', $open_id);
                })->first();
            return $data;
        }
    }

    //获取规则
    public function get_activity_info(Request $request) {
        $activity = new LuckMoney();
        $apiMessage = $activity->get_activity_info_by_id($request->id);
        return $apiMessage->send();
    }
}
